/**
 * Project Name:九色鹿
 * File Name:AuthController.java
 * Package Name:com.fxp.project.jiuselu.web.security.controller
 * Date:2021-08-29 12:51 下午
 * Copyright (c) 2021, Jason.Wang All Rights Reserved.
 */
package com.fxp.project.jiuselu.web.security.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fxp.project.jiuselu.commons.aes.AesUtil;
import com.fxp.project.jiuselu.commons.constant.ConstantCode;
import com.fxp.project.jiuselu.commons.name.Language;
import com.fxp.project.jiuselu.commons.name.RandomNameTool;
import com.fxp.project.jiuselu.commons.rsa.RsaUtil;
import com.fxp.project.jiuselu.commons.utils.CommonUtil;
import com.fxp.project.jiuselu.security.util.JwtTokenUtil;
import com.fxp.project.jiuselu.web.base.controller.BaseController;
import com.fxp.project.jiuselu.web.base.request.ReqBase;
import com.fxp.project.jiuselu.web.business.v1.pojo.InviteUserInfoVo;
import com.fxp.project.jiuselu.web.business.v1.pojo.UserInfoVo;
import com.fxp.project.jiuselu.web.config.CustomerApiConfig;
import com.fxp.project.jiuselu.web.config.WxMaConfiguration;
import com.fxp.project.jiuselu.web.domain.CommonResult;
import com.fxp.project.jiuselu.web.file.domain.FileUtil;
import com.fxp.project.jiuselu.web.models.order.entity.JslOrderGoods;
import com.fxp.project.jiuselu.web.models.order.entity.JslUserBalance;
import com.fxp.project.jiuselu.web.models.order.mapper.JslOrderGoodsMapper;
import com.fxp.project.jiuselu.web.models.order.mapper.JslOrderMapper;
import com.fxp.project.jiuselu.web.models.order.service.IJslOrderService;
import com.fxp.project.jiuselu.web.models.order.service.IJslUserBalanceService;
import com.fxp.project.jiuselu.web.models.order.vo.JslOrderVo;
import com.fxp.project.jiuselu.web.models.user.entity.JslPcUserOauth;
import com.fxp.project.jiuselu.web.models.user.entity.JslSaleInfo;
import com.fxp.project.jiuselu.web.models.user.entity.JslUser;
import com.fxp.project.jiuselu.web.models.user.entity.JslUserOauth;
import com.fxp.project.jiuselu.web.models.user.mapper.JslSaleInfoMapper;
import com.fxp.project.jiuselu.web.models.user.request.*;
import com.fxp.project.jiuselu.web.models.user.service.IJslPcUserOauthService;
import com.fxp.project.jiuselu.web.models.user.service.IJslSaleInfoService;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserOauthService;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserService;
import com.fxp.project.jiuselu.web.security.userdetails.CustomerUserDetails;
import lombok.Data;
import com.google.gson.internal.$Gson$Preconditions;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;

/**
 * ClassName: AuthController<br/>
 * Function: 授权登录管理<br/>
 * Date: 2021-08-29 12:51 下午<br/>
 *
 * @author Jason.Wang
 * @version 1.0.0.0
 * @see
 * @since JDK 1.8
 */
@Log4j2
@RestController
@RequestMapping("/v1/auth")
public class AuthController extends BaseController {

    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    IJslUserService jslUserService;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    CustomerApiConfig customerApiConfig;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    IJslUserOauthService jslUserOauthService;
    @Autowired
    IJslPcUserOauthService pcUserOauthService;

    public static void main(String[] args) throws Exception {
        String userPassword = new String(RsaUtil.decryptByPrivateKey(Base64.decodeBase64(
                "Br6nT3oWQ9xdRT1YZydxzFG7npkpxRGZrtejvBrkR1zWg2XBKBGzsos8T2LHKpAg6qeYwiaX+lRb8qqtyBT60A=="),
                "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAuKbB2aZs4WIHLdpdZjZf3VptUCZDnwpijqr19DYkn0qZt0l36ffyd5rnA3wRzF6boLO6ixPn0b1p7J0fDWz8NwIDAQABAkEAgitMTJq99sScOv7NCNkcC3dLyEyxLtSrVde/O0FP39oLosCAvSdhgug3lTMWpFgwUGtZ0MiO6gGqAn9E0SGFQQIhAOvp5WwMH//MxGChyj2sIAwVcuedzQU2U71dD5Neu4XTAiEAyF+FRhVjGqOxAkBM02t6KExf14OgsopMcGIbzRwbPY0CIDxYbDMjNtw8CM+fExiLevccVXQhzVvT9b+umllcFiO5AiBubvbtIWx1ijJMo1O0UlAJVc6c4Rb4T/DBH9FiwlLhIQIhANK2VYIfbaTrO2amyJq8kttcnTJC8kXp6JlgbepBVUfZ"),
                StandardCharsets.UTF_8);
        System.out.println(userPassword);
    }

    /**
     * login: 手机登录接口<br/>
     *
     * @param reqLogin
     * @param result
     * @return
     * @author Jason.Wang
     * @createTime 2020/3/14 16:37
     */
    @PostMapping("login")
    @CrossOrigin
    public CommonResult login(@RequestBody @Validated ReqLogin reqLogin, BindingResult result) {
        super.checkBindResult(result);
        // 当前对象为手机号+验证码、手机号+密码登录时需要检查当前用户是否存在
        // 当前账户采用验证码登录
        Integer level = null;
        switch (reqLogin.getStatus()) {
            case 0:
                level = 0;
                break;
            case 1:
                level = 1;
                break;
        }

        if (reqLogin.getType() == 1) {
            if (!super.validMobileCode(reqLogin.getMobile(), reqLogin.getCode())) {
                return CommonResult.validateFailed("验证码错误");
            }
        } else if (reqLogin.getType() == 2) {
//            JslUser jslUser = jslUserService.selectByUserPhone(reqLogin.getMobile());
            JslUser jslUser = jslUserService.getOne(new QueryWrapper<JslUser>().lambda().eq(JslUser::getUserPhone, reqLogin.getMobile()).eq(JslUser::getLevel, level));


            if (null == jslUser) {
                return CommonResult.failed("手机号未注册");
            }
            // 当前位手机号+ 密码登录方式
            String userPassword = null;
            String oldPasswork = null;
            try {
                userPassword = new String(RsaUtil.decryptByPrivateKey(Base64.decodeBase64(reqLogin.getPassword()),
                        customerApiConfig.getPrivateKey()), StandardCharsets.UTF_8);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (!passwordEncoder.matches(passwordEncoder.encode(userPassword), jslUser.getPassword())) {
                return CommonResult.failed("密码不正确");
            }
        }
        CustomerUserDetails userDetails =
                (CustomerUserDetails) userDetailsService.loadUserByUsername(reqLogin.getMobile() + "," + level);
        //        if (null != userDetails.getJslUser() && 1 == userDetails.getJslUser().getIsLock()) {
        //            return CommonResult.failed("当前用户被锁定");
        //        }

        if (userDetails.getJslUser() == null) {
            return CommonResult.failed("用户普通身份未注册");
        }

        //这里的认证信息应该是加密之前的。
        UsernamePasswordAuthenticationToken upToken =
                new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
//        String b = jslUserService.checkPhone(reqLogin.getMobile());
        Long b = null;
        try {
            b = jslUserService.getOne(new QueryWrapper<JslUser>().lambda().eq(JslUser::getUserPhone, reqLogin.getMobile()).eq(JslUser::getLevel, level)).getInviteId();
        } catch (Exception e) {
            b = null;
        }

        String invite = "";
        if (b == null) {
            invite = "false";
        } else {
            invite = "true";
        }
        Map<String, String> data = new HashMap<>();
        data.put("token", jwtTokenUtil.generateToken(userDetails));
        data.put("userId", super.getCurrentUserInfo().getUserId().toString());
        data.put("invite", invite);
        data.put("companyName", super.getCurrentUserInfo().getCompanyName());

        //状态更改为在线
        userDetails.getJslUser().setUserId(super.getCurrentUserInfo().getUserId());
        userDetails.getJslUser().setOnline(1);
        jslUserService.updateById(userDetails.getJslUser());

        return CommonResult.success(data);
    }

    /**
     * 查看邀请码的人
     *
     * @param inviteCode 邀请码
     * @return
     */
    @GetMapping("invite")
    @CrossOrigin
    public CommonResult selectinvite(String inviteCode) {
        Map<String, List> map = new HashMap();
        List<UserInfoVo> userInfoVos = jslUserService.selectUserByInvite(inviteCode);
        map.put("data", userInfoVos);
        return CommonResult.success(map);
    }

    @Autowired
    private IJslSaleInfoService jslSaleInfoService;

    /**
     * wxLogin: 微信登录的接口<br/>
     * wj处理用户和代理的微信登录
     *
     * @param reqWxLogin
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/12/26 21:11
     */
    @PostMapping("wxlogin")
    @CrossOrigin
    public CommonResult wxLogin(@RequestBody ReqWxLogin reqWxLogin, BindingResult result) {
        super.checkBindResult(result);
        final WxMaService wxService = WxMaConfiguration.getMaService(reqWxLogin.getAppId());
        if (StringUtils.isBlank(reqWxLogin.getJscode())) {
            return CommonResult.failed("微信授权码不能为空");
        }
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(reqWxLogin.getJscode());
            String openId = session.getOpenid();
            String unionId = session.getUnionid();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("token", null);
            jsonObject.put("userId", null);
            jsonObject.put("openId", openId);
            jsonObject.put("unionId", unionId);
            if (reqWxLogin.getType() == 1) {//代理尝试登录
                QueryWrapper<JslUserOauth> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openid", openId);
                queryWrapper.eq("oauth", 1);
                JslUserOauth jslsaleOauth = jslUserOauthService.getOne(queryWrapper);//代理绑定记录
                if (null == jslsaleOauth) {//代理没有绑定
                    jslsaleOauth = new JslUserOauth();
                    jslsaleOauth.setOauthType(1);
                    jslsaleOauth.setOauth("1");//代理标识
                    jslsaleOauth.setOpenid(openId);
                    jslsaleOauth.setUnionid(unionId);
                    jslUserOauthService.save(jslsaleOauth);//新增绑定记录
                    jsonObject.put("oauthId", jslsaleOauth.getId());
                    return CommonResult.success(jsonObject);
                } else if (null != jslsaleOauth.getUserId() && jslsaleOauth.getUserId() > 0) {//有绑定记录企且用户唯一标识不为null
                    JslSaleInfo jslSaleInfo = jslSaleInfoService.getOne(new QueryWrapper<JslSaleInfo>().lambda().eq(JslSaleInfo::getBindId, jslsaleOauth.getUserId()));
                    if (jslSaleInfo == null) {
                        jslSaleInfo = jslSaleInfoService.getOne(new QueryWrapper<JslSaleInfo>().lambda().eq(JslSaleInfo::getUserId, jslsaleOauth.getUserId()));
                    }
                    if (jslSaleInfo == null) {
                        return new CommonResult(503, "账户未存在，请账户中心注册代理人", null);
                    }
                    switch (jslSaleInfo.getStatus()) {
                        case 0:
                            return new CommonResult(501, "账户审核中", null);
                        case 2:
                            return new CommonResult(502, "账户审核失败，请重新提交", null);
                    }
                    CustomerUserDetails userDetails = (CustomerUserDetails) userDetailsService.loadUserByUsername(jslSaleInfo.getSalePhone() + "," + 1);
                    //这里的认证信息应该是加密之前的。
                    UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                    Authentication authentication = authenticationManager.authenticate(upToken);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    Map<String, String> data = new HashMap<>();
                    data.put("token", jwtTokenUtil.generateToken(userDetails));
                    data.put("userId", super.getCurrentUserInfo().getUserId().toString());
                    data.put("openId", openId);
                    data.put("unionId", unionId);
                    data.put("oauthId", jslsaleOauth.getId().toString());
                    data.put("companyName", super.getCurrentUserInfo().getCompanyName());

                    //状态更改为在线
                    userDetails.getJslUser().setUserId(super.getCurrentUserInfo().getUserId());
                    userDetails.getJslUser().setOnline(1);
                    jslUserService.updateById(userDetails.getJslUser());

                    return CommonResult.success(data);
                } else {//有记录未绑定成功的
                    jsonObject.put("oauthId", jslsaleOauth.getId());
                    return CommonResult.success(jsonObject);
                }
            } else {//用户尝试登录
                QueryWrapper<JslUserOauth> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openid", openId);
                queryWrapper.eq("oauth", 0);
                JslUserOauth jslUserOauth = jslUserOauthService.getOne(queryWrapper);//用户绑定记录
                if (null == jslUserOauth) {//用户没有绑定
                    jslUserOauth = new JslUserOauth();
                    jslUserOauth.setOauthType(1);
                    jslUserOauth.setOauth(reqWxLogin.getType().toString());//代理标识
                    jslUserOauth.setOpenid(openId);
                    jslUserOauth.setUnionid(unionId);
                    jslUserOauthService.save(jslUserOauth);//新增绑定记录
                    jsonObject.put("oauthId", jslUserOauth.getId());
                    return CommonResult.success(jsonObject);
                } else if (null != jslUserOauth.getUserId() && jslUserOauth.getUserId() > 0) {
                    JslUser jslUser = jslUserService.getById(jslUserOauth.getUserId());
                    if (null == jslUser) {
                        jsonObject.put("oauthId", jslUserOauth.getId());
                        return CommonResult.success(jsonObject);
                    }
                    CustomerUserDetails userDetails = (CustomerUserDetails) userDetailsService.loadUserByUsername(jslUser.getUserPhone() + "," + 0);
                    //这里的认证信息应该是加密之前的。
                    UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                    Authentication authentication = authenticationManager.authenticate(upToken);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    Map<String, String> data = new HashMap<>();
                    data.put("token", jwtTokenUtil.generateToken(userDetails));
                    data.put("userId", super.getCurrentUserInfo().getUserId().toString());
                    data.put("openId", openId);
                    data.put("unionId", unionId);
                    data.put("oauthId", jslUserOauth.getId().toString());
                    data.put("companyName", super.getCurrentUserInfo().getCompanyName());

                    //状态更改为在线
                    userDetails.getJslUser().setUserId(super.getCurrentUserInfo().getUserId());
                    userDetails.getJslUser().setOnline(1);
                    jslUserService.updateById(userDetails.getJslUser());

                    return CommonResult.success(data);
                } else {//有记录未绑定成功的
                    jsonObject.put("oauthId", jslUserOauth.getId());
                    return CommonResult.success(jsonObject);
                }
            }
        } catch (WxErrorException e) {
            return CommonResult.failed("微信授权信息配置出错");
        }
    }

    /**
     * wxLogin: 微信登录的接口<br/>
     * wj处理用户和代理的微信登录
     *
     * @param reqWxLogin
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/12/26 21:11
     */
    @PostMapping("dl/wxlogin")
    @CrossOrigin
    public CommonResult DLwxLogin(@RequestBody ReqWxLogin reqWxLogin, BindingResult result) {
        super.checkBindResult(result);
        final WxMaService wxService = WxMaConfiguration.getMaService(reqWxLogin.getAppId());
        if (StringUtils.isBlank(reqWxLogin.getJscode())) {
            return CommonResult.failed("微信授权码不能为空");
        }
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(reqWxLogin.getJscode());
            String openId = session.getOpenid();
            String unionId = session.getUnionid();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("token", null);
            jsonObject.put("userId", null);
            jsonObject.put("openId", openId);
            jsonObject.put("unionId", unionId);
            //代理尝试登录
            if ( reqWxLogin.getType()!=null && reqWxLogin.getType() == 1) {
                QueryWrapper<JslUserOauth> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openid", openId);
                queryWrapper.eq("oauth", 1);
                JslUserOauth jslsaleOauth = jslUserOauthService.getOne(queryWrapper);//代理绑定记录
                if (null == jslsaleOauth) {//代理没有绑定
                    jslsaleOauth = new JslUserOauth();
                    jslsaleOauth.setOauthType(1);
                    jslsaleOauth.setOauth("1");//代理标识
                    jslsaleOauth.setOpenid(openId);
                    jslsaleOauth.setUnionid(unionId);
                    jslUserOauthService.save(jslsaleOauth);//新增绑定记录
                    jsonObject.put("oauthId", jslsaleOauth.getId());
                    return CommonResult.success(jsonObject);
                } else if (null != jslsaleOauth.getUserId() && jslsaleOauth.getUserId() > 0) {//有绑定记录企且用户唯一标识不为null
                    if(null!=super.getCurrentUserInfo().getUserId()){
                        if(!jslsaleOauth.getUserId().equals(jslSaleInfoService.selectSaleInfoByBindId(super.getCurrentUserInfo().getUserId()).getUserId())){
                            return CommonResult.failed("当前微信已绑定账户信息");
                        }
                    }
                    JslSaleInfo jslSaleInfo = jslSaleInfoService.getOne(new QueryWrapper<JslSaleInfo>().lambda().eq(JslSaleInfo::getBindId, jslsaleOauth.getUserId()));
                    if (jslSaleInfo == null) {
                        jslSaleInfo = jslSaleInfoService.getOne(new QueryWrapper<JslSaleInfo>().lambda().eq(JslSaleInfo::getUserId, jslsaleOauth.getUserId()));
                    }
                    if (jslSaleInfo == null) {
                        return new CommonResult(503, "账户未存在，请账户中心注册代理人", null);
                    }
                    switch (jslSaleInfo.getStatus()) {
                        case 0:
                            return new CommonResult(501, "账户审核中", null);
                        case 2:
                            return new CommonResult(502, "账户审核失败，请重新提交", null);
                    }
                    CustomerUserDetails userDetails = (CustomerUserDetails) userDetailsService.loadUserByUsername(jslSaleInfo.getSalePhone() + "," + 1);
                    //这里的认证信息应该是加密之前的。
                    UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                    Authentication authentication = authenticationManager.authenticate(upToken);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    Map<String, String> data = new HashMap<>();
                    data.put("token", jwtTokenUtil.generateToken(userDetails));
                    data.put("userId", super.getCurrentUserInfo().getUserId().toString());
                    data.put("openId", openId);
                    data.put("unionId", unionId);
                    data.put("oauthId", jslsaleOauth.getId().toString());
                    data.put("companyName", super.getCurrentUserInfo().getCompanyName());
                    return CommonResult.success(data);
                } else {//有记录未绑定成功的
                    jsonObject.put("oauthId", jslsaleOauth.getId());
                    return CommonResult.success(jsonObject);
                }
            } else {//用户尝试登录
                QueryWrapper<JslUserOauth> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openid", openId);
                queryWrapper.eq("oauth", 0);
                queryWrapper.eq("oauth_type",1);
                JslUserOauth jslUserOauth = jslUserOauthService.getOne(queryWrapper);//用户绑定记录
                if (null == jslUserOauth) {//用户没有绑定
                    jslUserOauth = new JslUserOauth();
                    jslUserOauth.setOauthType(1);
                    if(reqWxLogin.getType()==null){
                        jslUserOauth.setOauth("0");//代理标识
                    }else{
                        jslUserOauth.setOauth(reqWxLogin.getType().toString());//代理标识
                    }
                    jslUserOauth.setOpenid(openId);
                    jslUserOauth.setUnionid(unionId);
                    jslUserOauthService.save(jslUserOauth);//新增绑定记录
                    jsonObject.put("oauthId", jslUserOauth.getId());
                    return CommonResult.success(jsonObject);
                } else if (null != jslUserOauth.getUserId() && jslUserOauth.getUserId() > 0) {
                    JslUser jslUser = jslUserService.getById(jslUserOauth.getUserId());
                    if (null == jslUser) {
                        jsonObject.put("oauthId", jslUserOauth.getId());
                        return CommonResult.success(jsonObject);
                    }
                    if(null!=super.getCurrentUserInfo().getUserId()){
                        if(!jslUserOauth.getUserId().equals(super.getCurrentUserInfo().getUserId())){
                            return CommonResult.failed("当前微信已绑定账户信息");
                        }
                    }
                    CustomerUserDetails userDetails = (CustomerUserDetails) userDetailsService.loadUserByUsername(jslUser.getUserPhone() + "," + 0);
                    //这里的认证信息应该是加密之前的。
                    UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                    Authentication authentication = authenticationManager.authenticate(upToken);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    Map<String, String> data = new HashMap<>();
                    data.put("token", jwtTokenUtil.generateToken(userDetails));
                    data.put("userId", super.getCurrentUserInfo().getUserId().toString());
                    data.put("openId", openId);
                    data.put("unionId", unionId);
                    data.put("oauthId", jslUserOauth.getId().toString());
                    data.put("companyName", super.getCurrentUserInfo().getCompanyName());
                    return CommonResult.success(data);
                } else {//有记录未绑定成功的
                    jsonObject.put("oauthId", jslUserOauth.getId());
                    return CommonResult.success(jsonObject);
                }
            }
        } catch (WxErrorException e) {
            return CommonResult.failed("微信授权信息配置出错");
        }
    }

    /**
     * wxBind: 微信绑定手机<br/>
     *
     * @param reqLogin
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/12/26 21:38
     */
    @PostMapping("wxbind")
    @CrossOrigin
    public CommonResult wxBind(@RequestBody @Validated ReqLogin reqLogin, BindingResult result) {
        super.checkBindResult(result);
        JslUserOauth jslUserOauth = jslUserOauthService.getById(reqLogin.getAuthId());
        if(null!=jslUserOauth.getUserId()&&reqLogin.getType()==0){
            if(jslUserOauth.getUserId().equals(super.getCurrentUserInfo().getUserId())){
                return CommonResult.failed( "当前微信已绑定账户信息");
            }
        }else if(null!=jslUserOauth.getUserId()&&reqLogin.getType()==1){
            if(jslUserOauth.getUserId().equals(jslSaleInfoService.selectSaleInfoByBindId(super.getCurrentUserInfo().getUserId()).getUserId())){
                return CommonResult.failed( "当前微信已绑定账户信息");
            }
        }
        if ("1".equals(jslUserOauth.getOauth())) {//是代理
            if (null != reqLogin.getCode()) {
                if (reqLogin.getType() == 1 && !super.validMobileCode(reqLogin.getMobile(), reqLogin.getCode())) {
                    return CommonResult.validateFailed("验证码错误");
                }
                if (null == jslUserOauth) {
                    return CommonResult.success( "请先进行微信登录");
                }
                if (null != jslUserOauth.getUserId() && 0 < jslUserOauth.getUserId()) {
                    return CommonResult.failed( "当前微信已绑定账户信息，请在个人中心进行操作");
                }
                JslSaleInfo jslSaleInfo = jslSaleInfoService.getOne(new QueryWrapper<JslSaleInfo>().lambda().eq(JslSaleInfo::getSalePhone, reqLogin.getMobile()));
                if (null == jslSaleInfo) {
                    return CommonResult.failed("手机号未注册");
                } else {
                    if (jslUserOauthService.list(new QueryWrapper<JslUserOauth>().eq("user_id",jslSaleInfo.getUserId()).eq("oauth", 1)).size() < 1) {
                        jslUserOauth.setUserId(jslSaleInfo.getUserId());
                        jslUserOauth.setOauth("1");
                        if (jslUserOauthService.updateById(jslUserOauth)) {
                            return CommonResult.success( "绑定成功，请登录");
                        } else return CommonResult.failed("绑定失败，请重试");
                    }else return CommonResult.failed( "当前微信已绑定账户信息");
                }
            } else {//登录后绑定
                if (null != jslUserOauth.getUserId() && 0 < jslUserOauth.getUserId()) {
                    return CommonResult.failed("当前微信已绑定账户信息，请在个人中心进行操作");
                } else {
                        jslUserOauth.setUserId(jslSaleInfoMapper.selectOne(new QueryWrapper<JslSaleInfo>().lambda().eq(JslSaleInfo::getBindId,super.getCurrentUserInfo().getUserId())).getUserId());
                        jslUserOauth.setOauth("1");
                    if (jslUserOauthService.updateById(jslUserOauth)) {
                        return CommonResult.success("绑定成功");
                    } else return CommonResult.failed("绑定失败，请重试");
                }
            }
        } else {//是用户
            if (null != reqLogin.getCode()) {
                if (reqLogin.getType() == 1 && !super.validMobileCode(reqLogin.getMobile(), reqLogin.getCode())) {
                    return CommonResult.validateFailed("验证码错误");
                }
                if (null == jslUserOauth) {
                    return CommonResult.success( "请先进行微信登录");
                }
                if (null != jslUserOauth.getUserId() && 0 < jslUserOauth.getUserId()) {
                    return CommonResult.failed("当前微信已绑定账户信息，请在个人中心进行操作");
                }
                JslUser jslUser = jslUserService.getOne(new QueryWrapper<JslUser>().lambda().eq(JslUser::getUserPhone, reqLogin.mobile).eq(JslUser::getLevel, 0));
                if (null == jslUser) {
                    return CommonResult.failed("手机号未注册");
                } else {
                    if (jslUserOauthService.list(new QueryWrapper<JslUserOauth>().eq("user_id", jslUser.getUserId()).eq("oauth", jslUser.getLevel())).size() < 1) {
                        jslUserOauth.setUserId(jslUser.getUserId());
                        jslUserOauth.setOauth("0");
                        if (jslUserOauthService.updateById(jslUserOauth)) {
                            return CommonResult.success( "绑定成功，请登录");
                        } else return CommonResult.failed("绑定失败，请重试");
                    }else return CommonResult.failed( "当前微信已绑定账户信息");
                }
            } else {//登录后绑定
//                查询是否有绑定记录
                JslUserOauth jslUserOauth1 = jslUserOauthService.getOne(new QueryWrapper<JslUserOauth>().lambda().eq(JslUserOauth::getUserId, super.getCurrentUserInfo().getUserId()).eq(JslUserOauth::getOauth, reqLogin.getType()).apply("id !="+jslUserOauth.getId()));
                if (!Optional.ofNullable(jslUserOauth1).isPresent()) {//不存在
//                    openid是否绑定
                    JslUserOauth jslUserOauth2 = jslUserOauthService.getOne(new QueryWrapper<JslUserOauth>().lambda().eq(JslUserOauth::getOpenid, jslUserOauth.getOpenid()).eq(JslUserOauth::getOauth, reqLogin.getType()).apply("id !="+jslUserOauth.getId()));
                    if (!Optional.ofNullable(jslUserOauth2).isPresent()) {//不存在
                        jslUserOauth.setUserId(super.getCurrentUserInfo().getUserId());
                        jslUserOauth.setOauth(reqLogin.getType() + "");
                        if (jslUserOauthService.updateById(jslUserOauth)) {
                            return CommonResult.success( "绑定成功");
                        } else return CommonResult.failed("绑定失败，请重试");
                    } else {
                        if (null == jslUserOauth2.getUserId()) {
                            jslUserOauth2.setUserId(super.getCurrentUserInfo().getUserId());
                            jslUserOauth2.setOauth(reqLogin.getType() + "");
                            if (jslUserOauthService.updateById(jslUserOauth2)) {
                                jslUserOauthService.removeById(jslUserOauth.getId());
                                return CommonResult.success( "绑定成功");
                            } else return CommonResult.failed("绑定失败，请重试");
                        } else return CommonResult.failed("微信已绑定");
                    }
                } else {
                    if (null == jslUserOauth1.getUserId()) {
                        jslUserOauth1.setUserId(super.getCurrentUserInfo().getUserId());
                        jslUserOauth1.setOpenid(jslUserOauth.getOpenid());
                        jslUserOauth1.setOauth(reqLogin.getType() + "");
                        if (jslUserOauthService.updateById(jslUserOauth1)) {
                            jslUserOauthService.removeById(jslUserOauth.getId());
                            return CommonResult.success( "绑定成功");
                        } else return CommonResult.failed("绑定失败，请重试");
                    } else return CommonResult.failed("微信已绑定");
                }
            }
        }
    }

    /**
     * wxBind: 微信结绑解绑<br/>
     *
     * @param reqWxLogin
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/12/26 21:38
     */
    @PostMapping("wxUnbound")
    @CrossOrigin
    public CommonResult wxUnbound(@RequestBody @Validated ReqWxLogin reqWxLogin, BindingResult result) {
        super.checkBindResult(result);
        final WxMaService wxService = WxMaConfiguration.getMaService(reqWxLogin.getAppId());
        if (StringUtils.isBlank(reqWxLogin.getJscode())) {
            return CommonResult.failed("微信授权码不能为空");
        }
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(reqWxLogin.getJscode());
            String openId = session.getOpenid();
            QueryWrapper<JslUserOauth> queryWrapper = new QueryWrapper<>();
            // 微信小程序
            queryWrapper.eq("oauth_type", 1);
            queryWrapper.eq("oauth", reqWxLogin.getType());
            queryWrapper.eq("openid", openId);
            // 查询当前微信用户信息有没有对应的用户数据信息
            boolean remove =false;
            if(reqWxLogin.getType()==0) {
                remove = jslUserOauthService.remove(new QueryWrapper<JslUserOauth>().lambda().eq(JslUserOauth::getOauth, reqWxLogin.getType()).eq(JslUserOauth::getUserId, super.getCurrentUserInfo().getUserId()));
            }else {
                remove = jslUserOauthService.remove(new QueryWrapper<JslUserOauth>().lambda().eq(JslUserOauth::getOauth, reqWxLogin.getType()).eq(JslUserOauth::getUserId,jslSaleInfoMapper.selectSaleInfoByBindId(super.getCurrentUserInfo().getUserId()).getUserId()));
            }if (remove) return CommonResult.success("微信解绑成功");
            else return CommonResult.failed("微信解绑失败");
        } catch (WxErrorException e) {
            return CommonResult.failed("微信授权信息配置出错");
        }
    }


    /**
     * siginUp: 注册用户<br/>
     *
     * @param reqLogin
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/9/14 9:54 下午
     */
    @PostMapping("siginup")
    @CrossOrigin
    public CommonResult siginUp(@RequestBody @Validated ReqLogin reqLogin, BindingResult result) {
        super.checkBindResult(result);
        if (!super.validMobileCode(reqLogin.getMobile(), reqLogin.getCode())) {
            return CommonResult.validateFailed("验证码错误");
        }

        if (jslUserService.saveUser(reqLogin)) {
            JslUser jslUser = jslUserService.selectByUserPhoneAndLevle(reqLogin.getMobile(),0);
            if(reqLogin.getType()==3 && reqLogin.getOpenId() !=null){
                JslPcUserOauth pcUserOauth=new JslPcUserOauth();
                pcUserOauth.setOpenId(reqLogin.getOpenId());
                if(jslUser != null){
                    pcUserOauth.setUserId(jslUser.getUserId());
                    pcUserOauth.setCreateTime(LocalDateTime.now());
                    pcUserOauthService.save(pcUserOauth);
                }
            }
            assert jslUser != null;
            return CommonResult.success(jslUser.getUserId());
        }
        return CommonResult.failed("注册失败，请重试");
    }

//    @PostMapping("test")
//    public void test(@RequestBody @Validated aaa str,BindingResult result){
//        super.checkBindResult(result);
////        JSONObject json = JSONObject.fromObject(str);
//        JslUser currentUserInfo1 = super.getCurrentUserInfo();
//        Date expiredDateFromToken = jwtTokenUtil.getExpiredDateFromToken(str.getToken());
//        System.err.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(expiredDateFromToken));
//        JslUser currentUserInfo = super.getCurrentUserInfo();
//        System.out.println("str = " + str);
//    }

    @Autowired
    private JslSaleInfoMapper jslSaleInfoMapper;
    @Autowired
    private IJslUserBalanceService jslUserBalance;
    @Autowired
    private JslOrderGoodsMapper jslOrderGoodsMapper;
    @Autowired
    private JslOrderMapper jslOrderMapper;

    @PostMapping("test")
    public void test() {
////        JSONObject json = JSONObject.fromObject(str);
////        JslUser currentUserInfo1 = super.getCurrentUserInfo();
//        Date expiredDateFromToken = jwtTokenUtil.getExpiredDateFromToken("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAxNiIsImNyZWF0ZWQiOjE2NTE3MzQ3ODYyNTEsImV4cCI6MTY1MTc2NDc4NiwiaWF0IjoxNjUxNzM0Nzg2fQ.46rGlQvL9qur6yCtaXnLgy1ov0NJPC6kMTNopsaeFLhBsMA_AWePCQrwSfUhWeFdhzXslQo8kM8bmawM-BPSgQ");
//        System.err.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(expiredDateFromToken));
////        JslUser currentUserInfo = super.getCurrentUserInfo();
////        System.out.println("str = " + str);

        jslOrderMapper.updatePayTime(LocalDateTime.now(),"QK20220518122531571571646");

    }

    @Data
    static class aaa extends ReqBase {
        String token;
    }

    @PostMapping("/getcode")
    @CrossOrigin
    public CommonResult url(){
        String qRcode = jslUserOauthService.getQRcode();
        System.out.println(qRcode);
        if(qRcode!=null){
            return CommonResult.success(qRcode,"获取成功!");
        }else {
            return CommonResult.failed("获取失败");
        }
    }

    @PostMapping("/getmes")
    @CrossOrigin
    public CommonResult token(HttpServletRequest request,HttpServletResponse response,String code,Integer type,Integer state){
        WxuserInfo wxuserInfo = jslUserOauthService.wxLogin(request, response, code,type,state);
//        System.out.println(accesstoken);
        if(wxuserInfo !=null){
            return CommonResult.success(wxuserInfo,"操作成功");
        }
        return CommonResult.failed("操作失败");
    }

    @PostMapping("/exit")
    @CrossOrigin
    public CommonResult update(String phone,String openId,String oauth) {

        JslUser jslUser = jslUserService.getOne(new QueryWrapper<JslUser>().eq("user_phone", phone).eq("level", oauth));
        QueryWrapper<JslUserOauth> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openId).eq("oauth",oauth);
        JslUserOauth one = jslUserOauthService.getOne(wrapper);
        if(one!=null){
            one.setUserId(jslUser.getUserId());
          return   CommonResult.success(jslUserOauthService.updateById(one));
        }
        return CommonResult.failed("未查询到该用户");
    }

    /**
     * pc微信绑定
     * @return
     */
    @PostMapping("bind")
    @CrossOrigin
    public CommonResult bind(@RequestBody @Validated BindUser bindUser, BindingResult result){
        super.checkBindResult(result);
        int i = jslUserOauthService.bundlingWx(bindUser.getOpenId(), super.getCurrentUserInfo().getUserId());
        if(i==0){
            return CommonResult.failed("绑定失败,请联系客服后重试");
        }
        return CommonResult.success("绑定成功");
    }

    /**
     * pc微信解绑
     */
    @PostMapping("end")
    @CrossOrigin
    public CommonResult endBind(Long userId){
        int i = jslUserOauthService.endBind(userId);
        if(i==0) return CommonResult.failed("解绑失败,请重新扫码登录后重试");
        return CommonResult.success("解绑成功");
    }

}
